package com.gogowan.agroenterprise.supply;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.base.BaseActivity;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.model.CollectionDescResultInfo;
import com.gogowan.agroenterprise.model.CollectionInfo;
import com.gogowan.agroenterprise.model.CollectionResultInfo;
import com.gogowan.agroenterprise.model.CollectionSDResultInfo;
import com.gogowan.agroenterprise.model.IntegrateQuestInfo;
import com.gogowan.agroenterprise.model.Message;
import com.gogowan.agroenterprise.supply.utils.MyListView;
import com.gogowan.agroenterprise.supply.utils.SupplyAndDemandUtils;
import com.gogowan.agroenterprise.supply.utils.MyListView.OnRefreshListener;
import com.gogowan.agroenterprise.utils.Utils;
/**
 * 推荐给我的求购信息
 * @author Maniac
 * 2012.12.24
 */
public class RecommDemandActivity extends BaseActivity{
	
	private MyListView list;
	private TextView textView;
	private BaseAdapter adapter;
	private ProgressDialog progressDialog;
	private SharedPreferences preferences;
	private long enterpriseId;
	private List<CollectionInfo> collectionInfos;
	private int selectedPosition = 0;
	
	private View bottom;
	private TextView bottomtv;
	private ProgressBar progressBar;
	private LinearLayout bottomLinear;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.supply_my_recommendations_d);
		
		list = (MyListView)findViewById(R.id.my_recommendation_dlist);
		textView = (TextView)findViewById(R.id.my_recommendations_dtext);
		collectionInfos = new ArrayList<CollectionInfo>();
		
		bottom = LayoutInflater.from(this).inflate(R.layout.itembottom,null);
		bottomtv = (TextView)bottom.findViewById(R.id.item_bottom_progress_tv);
		progressBar = (ProgressBar)bottom.findViewById(R.id.item_bottom_progressBar);
		bottomLinear = (LinearLayout)bottom.findViewById(R.id.item_bottom_ll);
		
		preferences = getSharedPreferences("LoginINfo", MODE_PRIVATE);
		enterpriseId = preferences.getLong("enterpriseid", 0);
		
		IntegrateQuestInfo info = new IntegrateQuestInfo();
		info.setEnterpriseID(enterpriseId);
		info.setSdType(1); //求购的
		info.setCid(0); //第一次请求
		GetListAsyn getListAsyn = new GetListAsyn(0,true);
		getListAsyn.execute(info);
		
		progressDialog = ProgressDialog.show(RecommDemandActivity.this,
				getString(R.string.alert_title),
				getString(R.string.alert_message), true, false);
		
		adapter = new BaseAdapter() {
			
			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				LayoutInflater inflater=(LayoutInflater)RecommDemandActivity.this.getSystemService(LAYOUT_INFLATER_SERVICE);
				View layout=inflater.inflate(R.layout.supply_list_item,null);
				TextView textView = (TextView)layout.findViewById(R.id.supply_list_item_text);
				TextView status = (TextView)layout.findViewById(R.id.supply_list_item_status);
				textView.setText(collectionInfos.get(position).getTitle());
				status.setText(collectionInfos.get(position).getTimeDown());
				return layout;
			}
			
			@Override
			public long getItemId(int position) {
				return position;
			}
			
			@Override
			public Object getItem(int position) {
				return collectionInfos.get(position);
			}
			
			@Override
			public int getCount() {
				return collectionInfos.size();
			}
		};
		
		list.setAdapter(adapter);
		
		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				
				selectedPosition = position-1;
				CollectionSDResultInfo cInfo = new CollectionSDResultInfo();
				cInfo.setCollectionID(collectionInfos.get(position-1).getCollectionID());
				
				progressDialog = ProgressDialog.show(RecommDemandActivity.this,
						getString(R.string.alert_title),
						getString(R.string.alert_message), true, false);
				
				GetCollectionDetail detail = new GetCollectionDetail();
				detail.execute(cInfo);
				
			}
		});
		
		list.setonRefreshListener(new OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				IntegrateQuestInfo info = new IntegrateQuestInfo();
				info.setEnterpriseID(enterpriseId);
				info.setSdType(1); //求购的
				info.setCid(0); //第一次请求
				GetListAsyn getListAsyn = new GetListAsyn(0,false);
				getListAsyn.execute(info);
			}
		});
		
		bottomLinear.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				loadRemainListItem(collectionInfos.get(collectionInfos.size() -1).getCollectionID());
			}
		});
	}

	private void loadRemainListItem(long sdId) {
		bottomtv.setText("正在加载更多.....");
		progressBar.setVisibility(View.VISIBLE);
		
		IntegrateQuestInfo info = new IntegrateQuestInfo();
		info.setEnterpriseID(enterpriseId);
		info.setSdType(1); //求购的
		info.setCid(sdId); //第一次请求
		
		GetListAsyn getListAsyn = new GetListAsyn(1,false);
		getListAsyn.execute(info);
	}
	
	/**
	 * 如果查看详细的时候删除掉该条信息，相应列表要更新
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (requestCode == 100) {
				collectionInfos.remove(selectedPosition);
				adapter.notifyDataSetChanged();
				if (collectionInfos == null || collectionInfos.size() == 0) {
					textView.setVisibility(View.VISIBLE);
					list.setVisibility(View.GONE);
				}
			}
		} 
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	/**
	 * 获取list 
	 * @author Administrator
	 *
	 */
	private class GetListAsyn extends MyAsyncTask{
		
		private int downMore;
		private boolean showProgress;
		public GetListAsyn(int downMore,boolean showProgress) {
			this.downMore = downMore;
			this.showProgress = showProgress;
		}
		
		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				if (showProgress) {
					progressDialog.dismiss();
					Toast.makeText(RecommDemandActivity.this, "服务器连接失败", Toast.LENGTH_LONG).show();
				} else {
					if (downMore == 0) {
						list.onRefreshComplete();
						Toast.makeText(RecommDemandActivity.this, "刷新失败", Toast.LENGTH_LONG).show();
					} else if (downMore == 1) {
						bottomtv.setText("更多");
						progressBar.setVisibility(View.GONE);
						Toast.makeText(RecommDemandActivity.this, "服务器连接失败", Toast.LENGTH_LONG).show();
					}
				}
			} else {
				
				Message message = (Message) Utils.fromJSON((String) res, Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					
					if (showProgress) {
						progressDialog.dismiss();
						Toast.makeText(RecommDemandActivity.this, "服务器连接失败", Toast.LENGTH_LONG).show();
					} else {
						if (downMore == 0) {
							list.onRefreshComplete();
							Toast.makeText(RecommDemandActivity.this, "刷新失败", Toast.LENGTH_LONG).show();
						} else if (downMore == 1) {
							bottomtv.setText("更多");
							progressBar.setVisibility(View.GONE);
							Toast.makeText(RecommDemandActivity.this, "服务器连接失败", Toast.LENGTH_LONG).show();
						}
					}
					
				} else {
					CollectionResultInfo materialResultInfo = (CollectionResultInfo)Utils.fromJSON(string, CollectionResultInfo.class);
					int result = materialResultInfo.getResult();
					if (result == 8610) {
						if (downMore == 0) {
							collectionInfos = materialResultInfo.getCollectionList();
							if (collectionInfos == null || collectionInfos.size() == 0) {
								if (showProgress) {
									Toast.makeText(RecommDemandActivity.this, "获取信息失败", Toast.LENGTH_LONG).show();
								} else {
									Toast.makeText(RecommDemandActivity.this, "刷新失败", Toast.LENGTH_LONG).show();
								}
							} else {
								textView.setVisibility(View.GONE);
								list.setVisibility(View.VISIBLE);
								adapter.notifyDataSetChanged();
								SupplyAndDemandUtils.addFooterView(adapter, RecommDemandActivity.this, list, bottom);
							}
							if (showProgress) {
								progressDialog.dismiss();
							} else {
								list.onRefreshComplete();
								Toast.makeText(RecommDemandActivity.this, "刷新成功", Toast.LENGTH_LONG).show();
							}
						} else if (downMore == 1) {
							List<CollectionInfo> cInfo = materialResultInfo.getCollectionList();
							for (int i = 0; i < cInfo.size(); i++) {
								collectionInfos.add(cInfo.get(i));
							}
							
							if (collectionInfos == null || collectionInfos.size() == 0) {
								Toast.makeText(RecommDemandActivity.this, "获取信息失败", Toast.LENGTH_LONG).show();
							} else {
								adapter.notifyDataSetChanged();
							}
							bottomtv.setText("更多");
							progressBar.setVisibility(View.GONE);
						}
					} else {
						if (showProgress) {
							progressDialog.dismiss();
							Toast.makeText(RecommDemandActivity.this, materialResultInfo.getResultinfo(), Toast.LENGTH_LONG).show();
						} else {
							if (downMore == 0) {
								list.onRefreshComplete();
								Toast.makeText(RecommDemandActivity.this, "刷新失败", Toast.LENGTH_LONG).show();
							} else if (downMore == 1) {
								bottomtv.setText("更多");
								progressBar.setVisibility(View.GONE);
								Toast.makeText(RecommDemandActivity.this, materialResultInfo.getResultinfo(), Toast.LENGTH_LONG).show();
							}
						}
					}
				}
			}
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			IntegrateQuestInfo request = (IntegrateQuestInfo)params[0];
			String json = Utils.toJSON(request);
			Message message = new Message(8600, true, json);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}
		
	}
	/**
	 * 查看详细
	 * @author Maniac
	 */
	private class GetCollectionDetail extends MyAsyncTask{

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(RecommDemandActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
			} else {
				
				Message message = (Message) Utils.fromJSON((String) res, Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					Toast.makeText(RecommDemandActivity.this, getString(R.string.analyse_error), Toast.LENGTH_LONG).show();
				} else {
					CollectionDescResultInfo materialResultInfo = (CollectionDescResultInfo)Utils.fromJSON(string, CollectionDescResultInfo.class);
					int result = materialResultInfo.getResult();
					if (result == 8710) {
						Intent intent = new Intent(RecommDemandActivity.this,RecommendationDetailActivity.class);
						intent.putExtra("CollectionDetail", string);
						intent.putExtra("Type", 1);
						startActivityForResult(intent, 100);
						Utils.randomAnim(RecommDemandActivity.this);
					} else {
						Toast.makeText(RecommDemandActivity.this, materialResultInfo.getResultinfo(), Toast.LENGTH_LONG).show();
					}
				}
			}
			
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			CollectionSDResultInfo request = (CollectionSDResultInfo)params[0];
			String json = Utils.toJSON(request);
			Message message = new Message(8700, true, json);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}
		
	} 
}
